package com.andnnl.guava;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class DelayTaskBuilder extends Thread {
    private static final Logger logger = LoggerFactory.getLogger(DelayTaskBuilder.class);
    public static final int MAX_RETRY_TIMES = 5;   //最大查询短信是否存在的重试次数
    private int retryTimes = 1;
    private DelayQueue<DelayTaskWrap> queue = new DelayQueue<>();
    //java 线程池
    private ExecutorService pool = Executors.newFixedThreadPool(10);

    private DelayTaskBuilder() {

    }

    public static DelayTaskBuilder newBuild() {
        return new DelayTaskBuilder();
    }

    public DelayTaskBuilder add(DelayTaskWrap t) {
        queue.add(t);
        return this;
    }

    public DelayTaskBuilder setMaxRetryTimes(int retryTimes) {
        this.retryTimes = retryTimes;
        return this;
    }

    public DelayTaskBuilder build() {
        this.start();
        return this;
    }

    @Override
    public void run() {
        logger.info("DelayTaskBuilder延时更新队列线程启动...");

        while (true) {
            try {
                DelayTaskWrap wrap = queue.poll();
                Callable task = wrap.getTask();
                Future f=pool.submit(task);
                f.get();
                //最多查询4次
                if (wrap.getRunCount() <= retryTimes) {
                    //将数据重新放回状态处理队列中
                    logger.info("retry time " + wrap.getRunCount() + " task:" + task);
//                        recvQueue.save(form);
                } else {
//                        logger.error("延时重试" + MAX_RETRY_TIMES + "次仍查询失败(可能为长短信后面部分状态):" + form.getSmsOperator() + "," + form.getSmsMsgid() + "," + form.getUserMblphone() + ","
//                                + form.getSmsStatus() + "," + form.getStatusCode() + "," + form.getEprId() + "," + form.getCpid());
                }
            } catch (Exception e) {
                logger.error("catch Exception:" + e.getMessage(), e);
            }

        }
    }


}
